/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Converter;

import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author iron
 */
@FacesConverter("CPFConverter")
public class CPFConverter implements Converter{

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        if(string.equals(""))
            return null;
        return Long.parseLong(string.replace(".", "").replace("-", ""));
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
    MaskFormatter mf;  
        try {
            mf = new MaskFormatter("###.###.###-##");
            mf.setValueContainsLiteralCharacters(false);
            String cpf = ((Long)o).toString();
            while(cpf.length()<11) {
                cpf="0"+cpf;
            }
            cpf = mf.valueToString(cpf); 
            return cpf;
        } catch (ParseException ex) {
            Logger.getLogger(CPFConverter.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    
    }
    
}
